package net.jielan188.hd.interceptor;

import net.jielan188.hd.bean.user.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

/**
 * 权限拦截
 */
public class CoreInterceptor implements HandlerInterceptor {

  public String[] allowUrls;//配置不拦截的资源
  public void setAllowUrls(String[] allowUrls) {
    this.allowUrls = allowUrls;
  }

  @Override
  public boolean preHandle( HttpServletRequest request, HttpServletResponse response, Object handler ) throws Exception {

    //查询当前请求是否属于不拦截范围
    String requestUrl = ".." + request.getRequestURI().replace( request.getContextPath(), "" );

    if( null != allowUrls && allowUrls.length >= 1 ){
      for( String url : allowUrls ) {
        if( requestUrl.contains( url ) ) {
          return true;
        }
      }
    }

    //判断用户是否登录过
    User userBean = (User)request.getSession().getAttribute( "currentUser" );
    if( userBean == null ){
      response.sendRedirect( request.getContextPath() + "/user/to_login" );
      return false;
    }

    //权限校验
    try {
      Subject subject = SecurityUtils.getSubject();
      subject.checkPermission(requestUrl);
      boolean pass = subject.isPermitted( requestUrl );
      if ( pass ) {
        return true;
      } else {
        response.getWriter().write("9999");
        return false;
      }
    }catch ( Exception e ){
      response.getWriter().write("9999");
      return false;
    }
  }

  @Override
  public void postHandle( HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView ) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

  }
}